class Solution {
public:
    string simplifyPath(string path) {
        //最后一个目录名没有斜杠
        while(path.length() && path[path.length() - 1] == '/')path.pop_back();

        stack<string>st;
        for(int i = 0; i < path.length(); ){
            string temp = "/";
            i++;
            while(i < path.length() && path[i] == '/')i++;
            while(i < path.length() && path[i] != '/'){
                temp += path[i++];
            }
            if(temp == "/.")continue;
            else if(temp == "/.."){
                if(st.size())st.pop();
            }
            else st.push(temp);
        }

        if(!st.size())return "/";

        string ans;
        stack<string>temp_st;
        while(!st.empty()){
            temp_st.push(st.top());
            st.pop();
        }
        while(!temp_st.empty()){
            ans += temp_st.top();
            temp_st.pop();
        }
        return ans;
    }
};

/**
 * 2022.1.6
 * 模拟，细心即可。
 */